package doan.chuyennganh.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import doan.chuyennganh.model.ClassStudent;
import doan.chuyennganh.model.ListClass;
import android.util.Pair;

public class SearchingHelper {
	
	
	public static void ApproximatString(String findString, ListClass list) {
		ArrayList<ClassStudent> res = new ArrayList<ClassStudent>();
		if(list == null ||findString == "" || findString == null){
			return;
		}
		
		ArrayList<Pair<Integer, ClassStudent>> dis = new ArrayList<Pair<Integer, ClassStudent>>();
		for(ClassStudent s:list.getAllClass()){
			int d = ApproximatDistance(s.getTenmonhoc()+ s.getMalop(), findString);
			dis.add(new Pair<Integer, ClassStudent>(d, s));
		}
		Collections.sort(dis, new Comparator<Pair<Integer, ClassStudent>>() {

			@Override
			public int compare(Pair<Integer, ClassStudent> lhs,
					Pair<Integer, ClassStudent> rhs) {
				return rhs.first.compareTo(lhs.first);
			}
		});
		for(int i = dis.size() - 1; i >= 0; i--){
			res.add(dis.get(i).second);
		}
		list.setList(res);
		//return list;
	}
	//s la chuoi nhap
	//s1 la chuoi da cho
	private static int ApproximatDistance(String s1, String s) {
		int saiSo = (int) Math.round(s.length() * 0.3f);

		int i, j, k, loi;
		i = j = loi = 0;
		while (i < s.length() && j < s1.length()) {
			if (s.charAt(i) != s1.charAt(j)) {
				loi++;
				for (k = 1; k <= saiSo; k++) {
					if ((i + k < s.length()) && s.charAt(i + k) == s1.charAt(j)) {
						i += k;
						loi += k - 1;
						break;
					} else if ((j + k < s1.length())
							&& s.charAt(i) == s1.charAt(j + k)) {
						j += k;
						loi += k - 1;
						break;
					}
				}
			}
			i++;
			j++;
		}
		loi += s.length() - i + s1.length() - j;
		return loi;
	}

}
